import json

from django.core import serializers
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.views import TokenObtainPairView
from django.contrib.auth.models import User

from core.decorators import log_action
from .models import Article
import datetime

from utils.response_utils import ResponseUtils  # 导入工具类


class CustomTokenObtainPairView(TokenObtainPairView):
    # 允许任何用户访问该视图，用于登录时无需认证
    permission_classes = [AllowAny]

    def post(self, request, *args, **kwargs):
        try:
            # 调用父类的 post 方法处理登录请求
            response = super().post(request, *args, **kwargs)
            return response
        except Exception as e:
            # 处理登录失败的情况，返回 401 未授权状态码
            return ResponseUtils.error_response(message='用户名或密码错误')


@api_view(['POST'])
@permission_classes([AllowAny])
def register(request):
    # 获取请求中的用户名和密码
    username = request.data.get('username')
    password = request.data.get('password')
    if not username or not password:
        # 如果用户名或密码为空，返回 400 错误请求状态码
        return ResponseUtils.error_response(message='用户名和密码是必需的')

    if User.objects.filter(username=username).exists():
        # 如果用户名已存在，返回 400 错误请求状态码
        return ResponseUtils.error_response(message='用户名已存在')

    # 创建新用户
    user = User.objects.create_user(username=username, password=password)
    # 生成刷新令牌
    refresh = RefreshToken.for_user(user)
    return ResponseUtils.success_response(data={
        'refresh': str(refresh),
        'access': str(refresh.access_token),
    })


# Create your views here.
def getMaps(request):
    if request.method == 'GET':
        area_code = request.GET.get('areaCode')
        return HttpResponse(f"参数值为:{area_code}")


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def getArticle(request):
    articleList = Article.objects.all()
    fields_to_extract = ['id', 'title', 'content', 'label', 'topic_id', 'create_time', 'user_id']
    # return queryset_to_json(articles, fields_to_extract)
    articles = serializers.serialize('python', articleList)
    # 手动添加 id 字段
    for i, article in enumerate(articles):
        article['fields']['id'] = articleList[i].id
    result = []
    for article in articles:
        # article_dict = model_to_dict(article, fields_to_extract)
        article_dict = article['fields']
        # 处理日期字段
        for key, value in article_dict.items():
            if isinstance(value, datetime.datetime):
                article_dict[key] = value.strftime('%Y-%m-%d')
        result.append(article_dict)

    return ResponseUtils.json_response(data=result)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
@csrf_exempt
def updateArticle(request):
    if request.method == 'POST':
        try:
            # 从请求体中获取 JSON 数据
            data = json.loads(request.body)
            # 假设实体参数中有 name 和 age 字段
            title = data.get('title')
            content = data.get('content')
            label = data.get('label')
            topic_id = data.get('topic_id')
            create_time = data.get('create_time')
            user_id = data.get('user_id')
            id = data.get('id')
            if id is not None:
                update_article(id, title, content, label, topic_id, create_time, user_id)
                return ResponseUtils.success_response(message="更新成功！")
        except json.JSONDecodeError:
            return ResponseUtils.error_response()
    return ResponseUtils.error_response()

    # 定义更新函数


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def update_article(id, title=None, content=None, label=None, topic_id=None, create_time=None, user_id=None):
    update_fields = {}
    if title:
        update_fields['title'] = title
    if content:
        update_fields['content'] = content
    if label:
        update_fields['label'] = label
    if topic_id:
        update_fields['topic_id'] = topic_id
    if create_time:
        update_fields['create_time'] = create_time

    if update_fields:
        Article.objects.filter(id=id).update(**update_fields)


'''
新增新闻信息
'''


def addArticle(request):
    if request.method == 'POST':
        try:
            # 从请求体中获取 JSON 数据
            data = json.loads(request.body)
            # 假设实体参数中有 name 和 age 字段
            title = data.get('title')
            content = data.get('content')
            label = data.get('label')
            topic_id = data.get('topic_id')
            create_time = data.get('create_time')
            user_id = data.get('user_id')
        except json.JSONDecodeError:
            return ResponseUtils.error_response()


'''
按照话题id分组统计
'''

'''
用户列表
'''


@log_action("用户管理-查询用户列表")
def getUseList(request):
    users = User.objects.all()
    userList = serializers.serialize('python', users)
    result = []
    for user in userList:
        # article_dict = model_to_dict(article, fields_to_extract)
        user_dict = user['fields']
        # 处理日期字段
        for key, value in user_dict.items():
            if isinstance(value, datetime.datetime):
                user_dict[key] = value.strftime('%Y-%m-%d')
        result.append(user_dict)

    return ResponseUtils.json_response(data=result)
